#include "tcp_client.hpp"
#include <iostream>


void TcpClient::Start(const EndPoint& peer)
{
    int fd = sock.Create(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
    dispatcher.AddConsumer(
        fd,
        EPOLLOUT,       // for judge connected event
        std::bind(&TcpClient::ConnEstabilished, this, std::placeholders::_1)
    );
    sock.Connect(peer);
    StartCmdLine(sock);
}
void TcpClient::StartCmdLine(const Socket& sock)
{
    cmdWorker = std::thread(
        [this, sock]()
        {
            while(1)
            {
                std::string cmd;
                std::cin >> cmd;
                sock.Send(cmd.c_str(), cmd.length());
            }
        }
    );
}

void TcpClient::ConnEstabilished(const Socket& sock)
{
    std::cout << "[Client] conn established" << std::endl;
    dispatcher.AddConsumer(
        sock.GetFd(),
        EPOLLIN,
        std::bind(&TcpClient::HandleMessage, this, std::placeholders::_1)
    );
}
void TcpClient::HandleMessage(const Socket& sock)
{
    char msg[200];
    int len = sock.Recv(msg, sizeof msg);
    if (len <= 0)       // peer closed
    {
        return;
    }
    std::cout << "[Client] Rcvd: " << msg << std::endl;
}



